package dianmobile.eistarandroid.ui.activities;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

import dianmobile.eistarandroid.ByhhAndroidApplication;
import dianmobile.eistarandroid.R;
import dianmobile.eistarandroid.beans.AccountEntity;
import dianmobile.eistarandroid.ui.Adapter.AccountListAdapter;
import dianmobile.eistarandroid.ui.views.SwipeActivity;
import dianmobile.eistarandroid.utils.ConstantsData;

public class ManageAccountActivity extends SwipeActivity {

    private ListView accountList;
    private List<AccountEntity> accountEntityList = new ArrayList<>();
    private AccountListAdapter adapter;
    private Button addAccount;
    private Button logout;
    private ImageButton back;
    private TextView edit;
    private boolean isEdit = false;

    private final String key = "account";
    private final String spName = "accounts";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_manage_account);

        initView();
    }

    @Override
    public boolean onKeyDown(int key, KeyEvent event){
        if (key == KeyEvent.KEYCODE_BACK) {
            onBackClick();
            return true;
        } else {
            return super.onKeyDown(key, event);
        }
    }
    private void initView() {
        accountList = (ListView)findViewById(R.id.lv_account_list);
        LayoutInflater inflater = getLayoutInflater();
        View footer = inflater.inflate(R.layout.list_footer_account, null);
        accountList.addFooterView(footer);
        addAccount = (Button)footer.findViewById(R.id.btn_add_account);
        logout = (Button)footer.findViewById(R.id.btn_logout);
        back = (ImageButton)findViewById(R.id.btn_back);
        edit = (TextView)findViewById(R.id.btn_edit_account);

        addAccount.setOnClickListener(new MyClickListener());
        logout.setOnClickListener(new MyClickListener());
        back.setOnClickListener(new MyClickListener());
        edit.setOnClickListener(new MyClickListener());
        initData();
        adapter = new AccountListAdapter(this, accountEntityList);
        accountList.setAdapter(adapter);
        accountList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AccountEntity item = accountEntityList.get(position);
                if (!item.isLogin()) {
                    String account = item.getAccount();
                    String password = item.getPassword();
                    Intent intent = new Intent(ManageAccountActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra("isForceToWaitUserInput", true);
                    intent.putExtra(ConstantsData.EXTRA_USER_NAME, account);
                    intent.putExtra("password", password);
                    startActivity(intent);
                    ManageAccountActivity.this.finish();
                }
            }
        });
    }

    /**
     * 保存当前登录的account
     */
    private void initData() {
        getAccountsData();
        SharedPreferences loginUserSp = getSharedPreferences(ConstantsData.DB_PER, MODE_PRIVATE);
        String loginAccount = loginUserSp.getString(ConstantsData.K_SAVED_ACCOUNT, "");
        String loginPassword = loginUserSp.getString(ConstantsData.K_SAVED_PASSWORD, "");
        AccountEntity item = new AccountEntity();
        item.setAccount(loginAccount);
        item.setPassword(loginPassword);
        item.setIsLogin(true);
        if(accountEntityList.contains(item)) {
            accountEntityList.remove(item);
        }
        accountEntityList.add(item);
        saveAccountsData();
    }
    private void getAccountsData() {
        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        String loginAccount = application.getLoginUserName();

        SharedPreferences sp = this.getSharedPreferences(spName, MODE_PRIVATE);
        String jsonString = sp.getString(key, null);
        List<AccountEntity> data = JSON.parseArray(jsonString, AccountEntity.class);
        if (data != null) {
            accountEntityList.addAll(data);
        }

        for (AccountEntity item : accountEntityList) {
            if (item.getAccount().equals(loginAccount)) {
                item.setIsLogin(true);
            } else {
                item.setIsLogin(false);
            }
        }
    }
    private void saveAccountsData() {
        SharedPreferences sp = getSharedPreferences(spName, MODE_PRIVATE);
        String jsonData = JSON.toJSONString(accountEntityList);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, jsonData);
        editor.commit();
    }
    private void addAccount() {
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_add_friends, (ViewGroup)findViewById(R.id.dialog_add_friends));
        final EditText account = (EditText)view.findViewById(R.id.edt_userid);
        final EditText password = (EditText)view.findViewById(R.id.edt_remark);
        password.setHint("输入密码");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加账号")
                .setView(view)
                .setPositiveButton("添加", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (account.getText().toString().equals("") || password.getText().toString().equals("")) {
                            return ;
                        }
                        AccountEntity item = new AccountEntity();
                        item.setAccount(account.getText().toString());
                        item.setPassword(password.getText().toString());
                        if(accountEntityList.contains(item)) {
                            accountEntityList.remove(item);     //如果存在该账号，则更新它的信息
                        }
                        accountEntityList.add(item);
                        adapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();
    }
    /**
     * 按下返回键的处理
     */
    private void onBackClick(){
        if(!isEdit) {
            saveAccountsData();
            ManageAccountActivity.this.finish();
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(ManageAccountActivity.this);
            builder.setTitle("是否保存修改？")
                    .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            saveAccountsData();
                            isEdit = false;
                            ManageAccountActivity.this.finish();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setNeutralButton("不保存", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            isEdit = false;
                            ManageAccountActivity.this.finish();
                        }
                    })
                    .create().show();
        }
    }

    class MyClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_add_account:
                    addAccount();
                    break;
                case R.id.btn_logout:
                    Intent intent = new Intent(ManageAccountActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra("isForceToWaitUserInput", true);
                    startActivity(intent);
                    ManageAccountActivity.this.finish();
                    break;
                case R.id.btn_back:
                    onBackClick();
                    break;
                case R.id.btn_edit_account:
                    if(isEdit) {
                        isEdit = false;
                        edit.setText("编辑");
                        saveAccountsData();
                        for (AccountEntity item : accountEntityList) {
                            item.setIsEdit(false);
                        }
                        adapter.notifyDataSetChanged();
                    } else {
                        isEdit = true;
                        edit.setText("完成");
                        for (AccountEntity item : accountEntityList) {
                            item.setIsEdit(true);
                        }
                        adapter.notifyDataSetChanged();
                    }
                    break;
                default:
                    break;
            }
        }

    }
}
